參考資料:
使 Laravel 除了原本 User
資料表外的資料表也可以當作紀錄登入資訊使用。
使用指令建立資料表:
php artisan make:migration create_admins_table
資料表內容如下:
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('username')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
使用指令建立 Model:
php artisan make:model Admin
Model 內引入 Illuminate\Foundation\Auth\User
後將 extends 改為 Authenticatable
,並設置 $guard
,完整內容如下:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
use HasFactory;
protected $guard = 'admin';
protected $fillable = [
'name', 'username', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
打開 config/auth.php
,並新增新的 guard 與 provider:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
...
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
],
使用指令建立 Seeder:
php artisan make:seeder CreateAdmin
打開 database/seeders/CreateAdmin.php
,並加入:
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
...
public function run()
{
DB::table('admins')->insert([
'name' => 'admin',
'username' => 'admin',
'password' => Hash::make('123456'),
]);
}
然後運行上面寫的 Seeder:
php artisan db:seed --class=CreateAdmin
這邊以 Livewire 為例:
namespace App\Http\Livewire\Auth;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
class Login extends Component
{
public $username;
public $password;
public $remember = false;
protected $rules = [
'username' => 'required',
'password' => 'required|min:6',
];
public function login()
{
if (Auth::guard('admin')->attempt($this->validate(), $this->remember)) {
// 登入成功
return redirect('/posts');
}
}
public function render()
{
return view('livewire.auth.login')
->layout('layouts.base');
}
}
開啟 routes/web.php
,並把要登入才能看得頁面套上 middleware:
Route::middleware(['auth:admin', 'auth.session'])->group(function () {
Route::get('/posts', App\Http\Livewire\Post\ShowPostList::class);
});